package cn.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import cn.biz.CartBiz;
import cn.biz.GoodsBiz;
import cn.biz.OrdergoodsBiz;
import cn.biz.OrdersBiz;
import cn.entity.Cart;
import cn.entity.Goods;
import cn.entity.Ordergoods;
import cn.entity.Orders;
import cn.entity.User;
import cn.util.CreatOrderNum;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class CartAction implements Action {
	private OrdersBiz ordersBiz;
	private OrdergoodsBiz ordergoodsBiz;
	private CartBiz cartBiz;
	private GoodsBiz goodsBiz;
	private List<Cart> Clist = new ArrayList<Cart>();
	private List<Goods> Glist = new ArrayList<Goods>();
	private String resultStr = "";
	private User user;
	private Integer[] CId;
	private Integer UId;
	private Integer[] GId;
	private Integer quantity;
	private String searchKey;
	//购物车根据卖家分组之后的结果
	private Map goodForShow = new HashMap<String, List<Cart>>();
	
	public Map getGoodForShow() {
		return goodForShow;
	}

	public void setGoodForShow(Map goodForShow) {
		this.goodForShow = goodForShow;
	}

	public OrdersBiz getOrdersBiz() {
		return ordersBiz;
	}

	public void setOrdersBiz(OrdersBiz ordersBiz) {
		this.ordersBiz = ordersBiz;
	}

	public OrdergoodsBiz getOrdergoodsBiz() {
		return ordergoodsBiz;
	}

	public void setOrdergoodsBiz(OrdergoodsBiz ordergoodsBiz) {
		this.ordergoodsBiz = ordergoodsBiz;
	}

	public String getResultStr() {
		return resultStr;
	}

	public void setResultStr(String resultStr) {
		this.resultStr = resultStr;
	}

	public Map<String, Object> getSession() {
		return ActionContext.getContext().getSession();
	}

	public User getSessionUser() {
		return (User) getSession().get("loginUser");
	}

	public CartBiz getCartBiz() {
		return cartBiz;
	}

	public void setCartBiz(CartBiz cartBiz) {
		this.cartBiz = cartBiz;
	}

	public GoodsBiz getGoodsBiz() {
		return goodsBiz;
	}

	public void setGoodsBiz(GoodsBiz goodsBiz) {
		this.goodsBiz = goodsBiz;
	}

	public List<Cart> getClist() {
		return Clist;
	}

	public void setClist(List<Cart> clist) {
		Clist = clist;
	}

	public List<Goods> getGlist() {
		return Glist;
	}

	public void setGlist(List<Goods> glist) {
		Glist = glist;
	}

	public User getUser() {
		return user;
	}

	public Integer[] getCId() {
		return CId;
	}

	public void setCId(Integer[] CId) {
		this.CId = CId;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Integer getUId() {
		return UId;
	}

	public void setUId(Integer UId) {
		this.UId = UId;
	}

	public Integer[] getGId() {
		return GId;
	}

	public void setGId(Integer[] GId) {
		this.GId = GId;
	}

	public Integer getQuantity() {
		return quantity;
	}

	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}

	public String getSearchKey() {
		return searchKey;
	}

	public void setSearchKey(String searchKey) {
		this.searchKey = searchKey;
	}
	
	/*
	 * 通过buyer的UId获取购物车信息 并跳转至用户购物车管理页面
	 */
	public String getCartListByBuyer() {
		if(StringUtils.isBlank(searchKey)||"请输入关键字".equals(searchKey)){
			Clist = cartBiz.queryByUser(getSessionUser());
		} else {
			Cart cart = new Cart();
			Goods goods = new Goods();
			goods.setGoodsname(searchKey);
			cart.setGoods(goods);
			cart.setUser(getSessionUser());
			Clist = cartBiz.query(cart);
		}
		return SUCCESS;
	}

	/*
	 * 添加商品到购物车操作
	 */
	public String addToCart() {
		goodForShow.clear(); 
		HttpServletRequest request = ServletActionContext.getRequest();
		Cart cart = new Cart();
		String GId = request.getParameter("goodId");
		String amount = request.getParameter("amount");
		
		cart.setGoods(goodsBiz.getGoodsById(Integer.valueOf(GId)));//商品
		cart.setUser(getSessionUser());//用户
		cart.setQuantity(Integer.valueOf(amount));//数量
		
		//首先获取当前用户在购物车中是否已有该商品
		List<Cart> cartList = cartBiz.getCartByGid(Integer.valueOf(GId),getSessionUser().getId());
		try{
			if(cartList.size()>0){//如果购物车中已有该商品了, 那就将数量叠加
				int newAmount = cartList.get(0).getQuantity() + Integer.valueOf(amount);
				cartList.get(0).setQuantity(newAmount);
				cartBiz.insertOrUpdate(cartList.get(0));
			}else{
				cartBiz.insertOrUpdate(cart);
			}
			resultStr = "({result:\"success\"})";
		}catch (Exception e) {
			// TODO: handle exception
			resultStr = "({result:\"failed\"})";
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/*
	 * 从购物车删除单/多个物品
	 */
	public String deleteFromCart() {
		for (Integer id : CId) {
			cartBiz.delete(id);
		}
		return SUCCESS;
	}
	
	/*购物车数量修改*/
	public String changeQuantity() {
		Cart cart = cartBiz.getCartById(CId[0]);
		cart.setQuantity(quantity);
		try {
			cartBiz.update(cart);
			resultStr = "{\"flag\":\"success\"}";
		} catch (Exception e) {
			resultStr = "{\"flag\":\"error\"}";
		}
		return SUCCESS;
	}
	
	/*
	 * 进入购物车结算页面, 同时创建相应数量订单
	 */
	public String cartSettle(){
		Map<String, Object> session = getSession();
		session.remove("awaitOrders");
		HttpServletRequest request = ServletActionContext.getRequest();
		
		//获取前端勾选中的购物车id数组
		String[] cids = request.getParameterValues("CId");
		
		//根据这个数组获取当前用户勾选的所有购物车条目信息
		List<Cart> carts = new ArrayList();
		for(String cid:cids){
			Cart cart = cartBiz.getCartById(Integer.valueOf(cid));
			carts.add(cart);
		}
		
		
		if(carts.size()>0){
			for(Cart cart: carts){
				String goodSellerName = String.valueOf(cart.getGoods().getUser().getName());
				
				//先判断该商品的卖家是否已经在
				if(goodForShow.containsKey(goodSellerName)){//如果这个卖家的条目已存在
					List<Cart> temp = (List)goodForShow.get(goodSellerName);
					temp.add(cart);
				}else{//如果不存在
					//创建一个list用于存放该卖家的购物车条目
					List<Cart> cartsOfThisSeller = new ArrayList();
					cartsOfThisSeller.add(cart);
					goodForShow.put(goodSellerName, cartsOfThisSeller);
					
				}
			}
		}
		//保存前台需要用到的订单单号
		StringBuffer orderNos = new StringBuffer();
		//遍历这个卖家-购物车条目分组 并开始创建订单
		Iterator it = goodForShow.keySet().iterator();  
		int i=0;
        while(it.hasNext()) {  
            String key = (String)it.next();  
            System.out.println("key: " + key);  
            System.out.println("list size: " + ((List)goodForShow.get(key)).size());  
            
            //创建新订单
            Orders o = new Orders();
            //设置订单号
            String orderno = CreatOrderNum.getOrderNumByUid(getSessionUser().getId());
            System.out.println("order no: "+orderno);
            o.setNum(orderno);
            //设置地址为空(待前端由用户进一步填写)
            o.setAddress("");
            //创建日期
            o.setCreDate(new Date());
            //初始删除状态为否
            o.setIsDelete(0);
            //设置状态为"待付款"
            o.setStatus("001");
            //设置买家
            o.setUser(getSessionUser());
            //先插入库中,以便后续对订单商品
            ordersBiz.insert(o);
            
            //计算总价, 遍历的同时将
            List<Cart> sellerCarts = (List)goodForShow.get(key);
            Float totalPrice = 0f;
            for(Cart cart:sellerCarts){
            	Float price = cart.getGoods().getPrice();
            	int quantity = cart.getQuantity();
            	totalPrice += (price * quantity);
            	Ordergoods og = new Ordergoods();
            	//创建该订单关联的商品
            	og.setGoods(cart.getGoods());
            	og.setOrders(o);
            	og.setName(cart.getGoods().getGoodsname());
            	og.setRemark(cart.getGoods().getRemark());
            	og.setPrice(cart.getGoods().getPrice());
            	og.setAmount(cart.getQuantity());
            	og.setUser(getSessionUser());
            	ordergoodsBiz.insert(og);
            }
            //设置总价
            o.setMoney(totalPrice);
            ordersBiz.update(o);
            List<Orders> savedOdr = ordersBiz.getOrdersByOrderNum(orderno);
            System.out.println("=== "+savedOdr.size());
            if(savedOdr.size()>0){
            	orderNos.append(savedOdr.get(0).getNum()+",");
            }
            
            i++;
        }  
        //订单完成, 因此删去相关购物车条目
        for(String cid:cids){
        	cartBiz.delete(Integer.valueOf(cid));
		}
        session.put("awaitOrders",orderNos.toString());
        session.put("cartGoods",goodForShow);
		return SUCCESS;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	
}
